/**
 * fulihui.com Inc.
 * Copyright (c) 2015-2016 All Rights Reserved.
 */
package com.fulihui.usercore.core.repository.impl;

import com.fulihui.usercore.biz.conv.GeneralConv;
import com.fulihui.usercore.core.repository.UserAddressExtRepository;
import com.fulihui.usercore.dal.dataobj.UserAddressExtDO;
import com.fulihui.usercore.dal.dataobj.UserAddressExtDOExample;
import com.fulihui.usercore.dal.mapper.UserAddressExtMapper;
import com.fulihui.usercore.dto.UserAddressExtDTO;
import com.fulihui.usercore.enums.CardTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @author zhangyingjie
 * @version $Id: v 0.1 2017年07月13日 16:39 zhangyingjie Exp $
 */
@Repository
public class UserAddressExtRepositoryImpl implements UserAddressExtRepository {
    @Autowired
    private UserAddressExtMapper userAddressExtMapper;
    @Override
    public boolean insert(UserAddressExtDTO dto) {
        //插入之前先查询 是否已经有认证信息
        UserAddressExtDTO userAddressExtDTO = this.queryByUserId(dto.getUserId());
        if (userAddressExtDTO == null){
            dto.setGmtCreate(new Date());
            dto.setGmtModified(new Date());
            dto.setCardType(CardTypeEnum.ID_CARD.getCode());
            int insert = userAddressExtMapper.insert(GeneralConv.conv(dto, UserAddressExtDO.class));
            if (insert>0){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean update(UserAddressExtDTO dto) {
        dto.setGmtModified(new Date());
        int i = userAddressExtMapper.updateByPrimaryKeySelective(GeneralConv.conv(dto, UserAddressExtDO.class));
        if (i>0){
            return true;
        }
        return false;
    }

    @Override
    public UserAddressExtDTO queryByUserId(String userId) {
        UserAddressExtDOExample example = new UserAddressExtDOExample();
        UserAddressExtDOExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<UserAddressExtDO> userAddressExtDOs = userAddressExtMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(userAddressExtDOs)){
            return GeneralConv.conv(userAddressExtDOs.get(0),UserAddressExtDTO.class);
        }
        return null;
    }
}
